"use strict"
const {sendStat, genRandomStr} = require("../extend/helper")
const jsonwebtoken = require("jsonwebtoken")
// let time = {}
// 防止 ddos 攻击, 最后oid为key 定时清除所有数据20s
// 检测过期时间, 频率太频繁拒绝(失败拒绝不更新上次时间)
/**
 * 游戏相关拦截器 token
 */
module.exports = () => {
	/**
   * @param {import("egg").Context } ctx
   */
	async function Auth(ctx, next) {
		let config = ctx.app.config
		let authKey = config.serverConfig.authKey
		let stat = false
		if (ctx.header.authorization) {
			let arr = ctx.header.authorization.split(" ")
			if (arr[0] == "prom_token" && arr.length == 2) {
				try {
					ctx.userInfo = jsonwebtoken.verify(arr[1], authKey)//,{ignoreNotBefore}
					if (ctx.userInfo.exp - Date.now() / 1000 < config.serverConfig.tokenTime * 0.66) {
						let {app_id, openid, oid, aid} = ctx.userInfo
						let token = jsonwebtoken.sign({app_id, openid, oid, aid, random: genRandomStr(20)}, config.serverConfig.authKey, {expiresIn: config.serverConfig.tokenTime})
						ctx.set("authorization", token)
					}
					let obj = await ctx.service.userCache.getWxSession(ctx.userInfo.oid)
					if (obj && obj.openid != ctx.userInfo.openid) {
						ctx.logger.error("对应的openid异常")
						throw new Error("对应的openid异常")
					}
				} catch (e) {
					ctx.status = 401
					// ctx.logger.error(ctx.get("X-Real-IP") + ":" + ctx.header.authorization + "\n" + e.message)
					ctx.body = sendStat(config.constant.ERROR_PERMISS_NOT_ALLOWED, "未授权" + e.message)
					return
				}

				ctx.validate({app_id: "string", random: "alphanum", openid: "string", oid: "number", aid: "number", }, ctx.userInfo)
				stat = true
				ctx.service.wechatUser.countLogin()
				await next()
				return
			}
		}
		if (!stat) {
			ctx.status = 401
			ctx.body = sendStat(config.constant.ERROR_PERMISS_NOT_ALLOWED, "未授权")
			return
		}
	}
	return Auth
}